﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;
using System.Xml.Linq;
 

namespace Twi.COMMON.WPF
{
    /// <summary>
    /// Interaction logic for DataImport.xaml
    /// </summary>
    public partial class DataImportDialog : Window
    {
        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);           

        private DataImporter _dataImporter;
        public DataImportDialog(DataImporter dataImporter)
        {
            InitializeComponent();
            _dataImporter = dataImporter;
        }


        private System.Threading.Thread thd;

        public void Import() 
        {
            Process();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
              
        }

        public void Process()
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx";
            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            
            thd = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {

                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(ofd.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
                try
                {
                    Dispatcher.Invoke(new Action(() =>
           {
               this.progressBar1.Maximum = worksheet.UsedRange.Rows.Count - 1;
               this.LblTotal.Content = worksheet.UsedRange.Rows.Count - 1;

               //Configure the ProgressBar
               this.progressBar1.Minimum = 0;

               progressBar1.Value = 0;

               //Stores the value of the ProgressBar
               progressBar1.ValueChanged += new RoutedPropertyChangedEventHandler<double>(progressBar1_ValueChanged);

               //Create a new instance of our ProgressBar Delegate that points
               // to the ProgressBar's SetValue method.
               UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);
               try
               {
                   for (int r = 2; r <= worksheet.UsedRange.Rows.Count; r++)
                   {
                       for (int c = 1; c <= worksheet.UsedRange.Columns.Count; c++)
                       {
                           string displayName = string.Format("{0}", ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, c]).Value);

                           string cellValue = string.Format("{0}", ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r, c]).Value ?? "");//不能出现空值

                           XElement xe = _dataImporter.XeEntity.Elements().First(x => x.Attribute("DisplayName").Value == displayName);
                           if (_dataImporter.DicConverter.Keys.Contains(xe.Name.LocalName))
                           {
                               cellValue = _dataImporter.DicConverter[xe.Name.LocalName](cellValue);
                           }
                           xe.SetValue(cellValue);
                       }
                       RequestResult rslt = _dataImporter.Persist(_dataImporter.XeEntity, "{0}" + Environment.NewLine + string.Format("第{0}行(包括标题行), 是否中止导入, 已导入的数据已经生效, 不会撤销! ", r));
                       if (rslt == RequestResult.ServerResultUnsuccessYes)
                       {
                           thd.Abort();
                           thd.Join();
                       }
                       Dispatcher.Invoke(updatePbDelegate,
                       System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, double.Parse((r - 1).ToString()) });
                   }
               }
               catch               
               {                   
                  //中断线程后会再一次调用已经释放的EXCEL对象
               }

           }));
                }
                finally
                {
                    IntPtr t = new IntPtr(excel.Hwnd);
                    int k = 0;
                    DllImportHelper.GetWindowThreadProcessId(t, out   k);
                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
                    p.Kill();
                }
            }));

            thd.Start();

        }

        void progressBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            this.LblCurrent.Content = e.NewValue;
        }
		

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("是否中止导入, 已导入的数据已经生效, 不会撤销! ", "系统提示", MessageBoxButton.YesNo)
            thd.Abort();
            thd.Join();
        }

     
        
    }
}
